package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.seach.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CC
 * time 2024-05-07
 * description
 */
@Service
@Transactional
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleService apArticleService;

    @Override
    @Async
    public void buildArticleToMinio(ApArticle apArticle, String content) {
        if (StringUtils.hasText(content)) {
            try {
                Template template = configuration.getTemplate("article.ftl");
                Map<String,Object> data =new HashMap<>();
                StringWriter stringWriter = new StringWriter();
                template.process(data,stringWriter);
                InputStream in = new ByteArrayInputStream(stringWriter.toString().getBytes());
                String res = fileStorageService.uploadHtmlFile("", apArticle.getId()+".html", in);

                apArticleService.update(Wrappers.lambdaUpdate(ApArticle.class)
                        .eq(ApArticle::getId, apArticle.getId()).set(ApArticle::getStaticUrl, res));

                //发送消息,创建ES索引
                createArticleESIndex(apArticle,content,res);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


    }
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    private void createArticleESIndex(ApArticle apArticle, String content, String res) {
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,searchArticleVo);
        searchArticleVo.setContent(content);
        searchArticleVo.setStaticUrl(res);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
    }
}
